package com.zzyl.framework.interceptor;

import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 小程序端Token拦截器
 * @author ghy
 * @version 1.0
 * @since 2025-08-20 15:17
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 拦截作用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 是一个真正handler，就是Controller标记了RequestMapping注解的方法
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1.获取token
        String token = request.getHeader("authorization");
        // 2.判断token是否有效
        if(StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = tokenService.parseToken(token);
            if(Objects.isNull(claims)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            Object memberId = claims.get("memberId");
            if(Objects.isNull(memberId)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            // token有效且能够解析出登录的老人家属ID
            MemberThreadLocal.setMemberId(Long.valueOf(memberId.toString()));
            log.info("小程序端登录的老人家属ID:{}", memberId);
        } catch (Exception e) {
            log.error("token解析异常:{}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    /**
     * 释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 避免内存泄漏
        MemberThreadLocal.remove();
    }
}
